<?php
global $smarty;

$thisPage = "confirm";

TemplateHelper::useLayout("default", true);


$confirmTypes = array();
$confirmTypes[] = array(type => "user", title => "User access rights", content => getTabContent("user", $smarty));
$confirmTypes[] = array(type => "profile", title => "Export/import confirmation", content => getTabcontent("profile", $smarty));
$confirmTypes[] = array(type => "recommendation", title => "Recommendation confirmation", content => getTabContent("recommendation", $smarty));
$confirmTypes[] = array(type => "businesslead", title => "Business lead confirmation", content => getTabContent("businesslead", $smarty));
$confirmTypes[] = array(type => "habroad", title => "Abroad company confirmation", content => getTabContent("habroad", $smarty));
$confirmTypes[] = array(type => "sponsor", title => "Invoice", content => getTabContent("sponsor", $smarty));

adddataservice("getuserlist");
addDataservice("getprofilelist");
addDataservice("getrecommendationlist");
addDataservice("getbusinessleadlist");
addDataservice("toggleadmin");
addDataservice("toggleactive");
addDataService("getchanges");
addDataService("acceptchanges");
addDataService("rejectchanges");
addDataService("toggleaccept");
addDataService("gethabroadlist");
addDataService("getsponsorlist");

function buildLayout($smarty) {
    $smarty->assign("default", array(
        content => getContent($smarty),
        contexthelp => getContextHelp($smarty),
    ));
}

function executeService($serviceName, $params) {
    switch ($serviceName) {
        case "getuserlist" : { return service_getuserlist($params); }
        case "gethabroadlist" : { return service_gethabroadlist($params); }
        case "getsponsorlist" : { return service_getsponsorlist($params); }
        case "getprofilelist" : { return service_getprofilelist($params); }
        case "getrecommendationlist" : { return service_getrecommendationlist($params); }
        case "getbusinessleadlist" : { return service_getbusinessleadlist($params); }
        case "toggleadmin" : { return service_toggleadmin($params); }
        case "toggleactive" : { return service_toggleactive($params); }
        case "getchanges" : { return service_getchanges($params); }
        case "acceptchanges" : { return service_acceptchanges($params); }
        case "rejectchanges" : { return service_rejectchanges($params); }
        case "toggleaccept" : { return service_toggleAccept($params); }
    }
}

function getTabContent($tabName, $smarty) {
    switch ($tabName) {
        case "user" : { return getUserTabcontent($smarty); }
        case "profile" : { return getProfileTabContent($smarty); }
        case "recommendation" : { return getRecommendationTabContent($smarty); }
        case "businesslead" : { return getBusinessleadTabContent($smarty); }
        case "habroad" : { return getHAbroadTabContent($smarty); }
        case "sponsor" : { return getSponsorTabContent($smarty); }
    }
}

function getUserTabContent($smarty) {
    global $thisPage;

    return $smarty->fetch(TemplateHelper::getTemplateFile($thisPage, "tab.user", true));
}

function getProfileTabContent($smarty) {
    global $thisPage;

    return $smarty->fetch(TemplateHelper::getTemplateFile($thisPage, "tab.profile", true));
}

function getRecommendationTabContent($smarty) {
    global $thisPage;

    return $smarty->fetch(TemplateHelper::getTemplateFile($thisPage, "tab.recommendation", true));
}

function getBusinessleadTabContent($smarty) {
    global $thisPage;

    return $smarty->fetch(TemplateHelper::getTemplateFile($thisPage, "tab.businesslead", true));
}

function getHAbroadTabContent($smarty) {
    global $thisPage;

    return $smarty->fetch(TemplateHelper::getTemplateFile($thisPage, "tab.habroad", true));
}

function getSponsorTabContent($smarty) {
    global $thisPage;

    return $smarty->fetch(TemplateHelper::getTemplateFile($thisPage, "tab.sponsor", true));
}

function service_acceptchanges($params) {
    if ($params['type'] == "profile") {
        Database::loadModel("companies");
        Database::getModel()->acceptChanges($params['id']);
    } else if ($params['type'] == "businesslead") {
        Database::loadModel("businessleads");
        Database::getModel()->acceptChanges($params['id']);
        $companyId = Database::getModel()->getCompanyId($params['id']);
        Database::loadModel("companies");
        Database::getModel()->acceptChanges($companyId);
    } else if ($params['type'] == "recommendation") {
        Database::loadModel("recommended_services");
        Database::getModel()->acceptChanges($params['id']);
        $companyId = Database::getModel()->getCompanyId($params['id']);
        Database::loadModel("companies");
        Database::getModel()->acceptChanges($companyId);
    } else if ($params['type'] == "habroad") {
        Database::loadModel("companies");
        Database::getModel()->acceptChanges($params['id']);
    } else if ($params['type'] == "sponsor") {
        Database::loadModel("payment");
        Database::getModel()->removePayedInvoicesFor($params['id']);
        Database::loadModel("companies");
        Database::getModel()->acceptSponsorchanges($params['id']);
//        createInvoiceFor($params['id'], $amount);
    }
    $content = array();
    $stat = Database::getModel()->getHeadStatistics();
    $content[] = "<?php";
    $content[] = 'global $stat;';
    $content[] = '$stat[\'companycount\'] = '.$stat['companycount'] . ";";
    $content[] = '$stat[\'categorycount\'] = '.$stat['categorycount'] . ";";
    $f = fopen("site/resources/stat.php", "w");
    for ($i = 0; $i < count($content); $i++) {
        fputs($f, $content[$i] . "\r\n");
    }
    fclose($f);
    return serviceSuccessful(array(
    ));
}

function service_rejectchanges($params) {
    if ($params['type'] == "profile") {
        Database::loadModel("companies");
        Database::getModel()->rejectChanges($params['id']);
    } else if ($params['type'] == "businesslead") {
        Database::loadModel("businessleads");
        Database::getModel()->rejectChanges($params['id']);
        $companyId = Database::getModel()->getCompanyId($params['id']);
        Database::loadModel("companies");
        Database::getModel()->rejectChanges($companyId);
    } else if ($params['type'] == "recommendation") {
        Database::loadModel("recommended_services");
        Database::getModel()->rejectChanges($params['id']);
        $companyId = Database::getModel()->getCompanyId($params['id']);
        Database::loadModel("companies");
        Database::getModel()->rejectChanges($companyId);
    }
    return serviceSuccessful(array(
    ));
}

function createInvoiceFor($id, $amount) {
    Log::debug("start invoice creation");
    $invoiceData = getConfigParameter("site", "invoiceData");
    $baseURL = getConfigParameter("directories", "baseURL");
    $sellerData = $invoiceData['sellerData'];
    Database::loadModel("companies");
    $clientData = Database::getModel()->getClientData($id);
    $invoice = new Invoice();
    $invoice->setElado($sellerData['name'], new Address(
        $sellerData['country'],
        $sellerData['city'],
        $sellerData['zipcode'],
        $sellerData['street'],
        $sellerData['sttype'],
        $sellerData['houseno']
    ), $sellerData['taxno']);
    $invoice->setVevo($clientData['companyname'], new Address(
        $clientData['country'],
        $clientData['city'],
        $sellerData['zipcode'],
        $clientData['street'],
        $clientData['sttype'],
        $clientData['houseno']
    ), $clientData['taxno']);
    $invoice->setSzamlainfo(getInvoiceNumber(), date("Y-m-d"), date("Y-m-d"), getPaymentDeadline(), $invoiceData['paymentMethod'], false);
    $invoice->addTetel("Hirdetési szolgáltatás", $amount, $invoiceData['VAT']);
    $invoice->calculateOsszesites();
    $sid = InvoiceAuth::startSession($invoiceData['username'], $invoiceData['password']);
    if ($clientData['eszamla_username'] == "") {
        InvoiceAdministration::setSID($sid);
        $result = InvoiceAdministration::registerCustomer($clientData['companyname'], $clientData['email'], $clientData['taxno']);
        $clientData['eszamla_username'] = $result['username'];
        Database::loadModel("user");
        Database::getModel()->setInvoiceUser(Auth::getUserProperty("user_id"), $result['username']);
    }
    InvoiceService::setSID($sid);
    InvoiceService::uploadInvoice($clientData['eszamla_username'], $invoice);
//    $payUrl = InvoiceService::pay($clientData['eszamla_username'], $invoice->getInvoiceNumber(), $invoice->getGrossPayment(), "HUF", $baseURL);
//    log::debug("Pay URL=$payUrl");
/*
    sendEmail("invoice", $clientData['email'], array(
        firstname => getUserProperty("firstname"),
        lastname => getUserproperty("lastname"),
        title => getUserProperty("title"),
        link => $payUrl,
    ));
*/
    InvoiceAuth::endSession();
    Database::loadModel("companies");
    Log::debug("Invoice created");
}

function getInvoiceNumber() {
    $invoiceData = getConfigParameter("site", "invoiceData");
    Database::loadModel("misc");
    $counter = Database::getModel()->getInvoiceNumber();
    return $invoiceData['invoicePrefix'] . "-" . $counter;
}

function getPaymentDeadline() {
    $invoiceData = getconfigParameter("site", "invoiceData");
    return date("Y-m-d", time() + $invoiceData['paymentDeadline'] * 24*60*60);
}

function service_getchanges($params) {
    $result = array();
    if ($params['type'] == "profile") {
        Database::loadmodel("companies");
        $result = Database::getModel()->getChanges($params['id']);
    } else if ($params['type'] == "businesslead") {
        Database::loadmodel("businessleads");
        $result = Database::getModel()->getChanges($params['id']);
    }
    return serviceSuccessful(array(
        data => $result,
    ));
}

function service_toggleadmin($params) {
    Database::loadModel("user");
    if ($params['operation'] == "add") {
        Database::getModel()->setAdmin($params['userid']);
    } else {
        Database::getModel()->clearAdmin($params['userid']);
    }
    return serviceSuccessful(array(
    ));
}

function service_toggleactive($params) {
    Database::loadModel("user");
    if ($params['operation'] == "activate") {
        Database::getModel()->activateUser($params['userid']);
    } else {
        Database::getModel()->deactivateUser($params['userid']);
    }
    return serviceSuccessful(array(
    ));
}

function service_toggleaccept($params) {
    if ($params['type'] == "recommendations") {
        Database::loadModel("recommended_services");
    }
    if ($params['operation'] == "add") {
        Database::accept($params['id']);
    } else if ($params['operation'] == "remove") {
        Database::reject($params['id']);
    }
    return serviceSuccessful(array(
    ));
}

function service_getsponsorlist($params) {
    Database::loadModel("payment");
    $result = Database::getModel()->getPayedInvoices();
    $limit = intval(getRequestParameter("rows"), 10);
    $reccount = Database::getModel()->getPayedInvoicesCount();
    return array(
        page => getRequestParameter("pg"),
        total => ceil($reccount / $limit),
        records => $reccount,
        rows => JQGridHelper::convert($result, "company_id"),
    );
}

function service_getuserlist($params) {
    Database::loadModel("user");
    Database::getModel()->setPageData(getRequestParameter("pg"), getRequestParameter("rows"));
    $result = Database::getAll("true", array(), "UserAdminFormatter");
    $limit = intval(getRequestParameter("rows"), 10);
    $reccount = Database::getAllCount();
    return array(
        page => getRequestParameter("pg"),
        total => ceil($reccount / $limit),
        records => $reccount,
        rows => $result
    );
}

function service_gethabroadlist($params) {
    Database::loadModel("companies");
    $result = Database::getModel()->getHAUpdateRequests();
    $limit = intval(getRequestParameter("rows"), 10);
    $reccount = Database::getModel()->getHAUpdateRequestCount();
    return array(
        page => getRequestParameter("pg"),
        total => ceil($reccount / $limit),
        records => $reccount,
        rows => $result
    );
}

function service_getrecommendationlist($params) {
    Database::loadModel("recommended_services");
    Database::getModel()->setPageData(getRequestParameter("pg"), getRequestParameter("rows"));
    $result = Database::getModel()->getUpdateRequests();
//    $result = Database::getAll("true", array(), "RecServAdminFormatter", true);
    $limit = intval(getRequestParameter("rows"), 10);
    $reccount = Database::getAllCount();
    return array(
        page => getRequestParameter("pg"),
        total => ceil($reccount / $limit),
        records => $reccount,
        rows => $result,
    );
}

function service_getProfileList($params) {
    Database::loadModel("companies");
    $result = Database::getModel()->getUpdateRequests();
    $limit = intval(getRequestParameter("rows"), 10);
    $reccount = Database::getModel()->getUpdateRequestCount();
    return array(
        page => getRequestParameter("pg"),
        total => ceil($reccount / $limit),
        records => $reccount,
        rows => $result
    );
}

function service_getBusinessLeadList($params) {
    Database::loadModel("businessleads");
    $result = Database::getModel()->getUpdateRequests();
    $limit = intval(getRequestParameter("rows"), 10);
    $reccount = Database::getModel()->getUpdateRequestCount();
    return array(
        page => getRequestParameter("pg"),
        total => ceil($reccount / $limit),
        records => $reccount,
        rows => $result
    );
}

function getContent($smarty) {
    global $thisPage;
    global $confirmTypes;
    
    $smarty->assign("confirmtypes", $confirmTypes);
    return $smarty->fetch(TemplateHelper::getTemplateFile($thisPage, "content", true));
}

function getContextHelp($smarty) {
    global $thisPage;
    
    return $smarty->fetch(TemplateHelper::getTemplateFile($thisPage, "contexthelp", true));
}

function getPageHeader() {
}

function getPageFooter() {
}

?>
